// import { request,imageUrl,baseUrl,getsign,storage,native_navigation} from './request.js'
import * as request_data from './request.js'

//乘法精度计算	 
const bcmul = (a, b) => {
	var c = 0,
		d = a.toString(),
		e = b.toString();
	try {
		c += d.split(".")[1].length
	} catch (f) {}
	try {
		c += e.split(".")[1].length
	} catch (f) {}
	return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c)
}

//加法精度计算
const bcadd = (a, b) => {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length
	} catch (f) {
		c = 0
	}
	try {
		d = b.toString().split(".")[1].length
	} catch (f) {
		d = 0
	}
	return e = Math.pow(10, Math.max(c, d)), (bcmul(a, e) + bcmul(b, e)) / e
}

//减法精度计算
const bcsub = (a, b) => {
	var c, d, e;
	try {
		c = a.toString().split(".")[1].length
	} catch (f) {
		c = 0
	}
	try {
		d = b.toString().split(".")[1].length
	} catch (f) {
		d = 0
	}
	return e = Math.pow(10, Math.max(c, d)), (bcmul(a, e) - bcmul(b, e)) / e
}

//统一提示方便全局修改	
const msg = (title, duration = 1500, mask = false, icon = 'none') => {
	if (Boolean(title) === false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

//页面返回
const back = index => {
	uni.navigateBack({
		delta: index
	});
}

//页面跳转
const on = url => {
	let urls = request_data.native_navigation
	if (urls.includes(url)) {
		uni.switchTab({
			url
		})
	} else {
		uni.navigateTo({
			url
		})
	}

}

//解析地址 获取地址中的所有参数
const ons = (url) => {
	let obj = {}
	let reg = /([^?=&]+)=([^?=&]+)/g
	url.replace(reg, (...arg) => {
		obj[arg[1]] = arg[2]
	})
	return obj
}

// 跳转链接方法
// 传入参数说明
// url 类型：string 需要跳转的链接地址
// type 类型：int 参数可为空 代表不同的跳转方式
// obj 类型：object 参数可为空 所有跳转数据对象
const gotos = (url, type = '', obj = {}) => {
	if (type == '') {
		let query = ons(url)
		console.log(query)
		let http = /^http/.test(url)
		if (http) {
			let src = '/pages/webview/webview?url=' + url //中转页web-view
			on(src);
		} else if (query.appid) { //打开小程序
			uni.navigateToMiniProgram({
				appId: query.appid,
				path: query.url,
				extraData: {
					foo: 'bar'
				},
				envVersion: 'develop',
				success(res) {
					// 打开成功
				}
			})
		} else {
			on(url);
		}
	}

	if (type == 1) {
		//暂定为APP端打开第三方APP功能
		//该方法要求obj参数包含
		//pname 安卓应用包名
		//androidurl 安卓应用下载链接
		//urlscheme IOS唤醒协议头名称
		//iosurl 苹果应用市场地址
		let browser
		// #ifdef APP-PLUS
		if (uni.getSystemInfoSync().platform == "android") {
			plus.runtime.launchApplication({
					pname: obj.pname,
				},
				function() {
					uni.showModal({
						title: '提示',
						content: '应用尚未安装，是否前往安装',
						success: function(res) {
							if (res.confirm) {
								browser = getbrowser()
								console.log(browser)
								if (!browser) {
									uni.showModal({
										title: '提示',
										content: '没有安装合适的浏览器，请联系管理员添加!',
										success: function(res) {

										}
									});
								}

								//需要打开默认浏览器应用，进行处理
								plus.runtime.openURL(obj.androidurl,
									function() {
										console.log('打开失败')
									}, browser)
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				})
		}
		if (uni.getSystemInfoSync().platform == "ios") {
			plus.runtime.openURL(obj.urlscheme, function() {
				uni.showModal({
					title: '提示',
					content: '应用尚未安装，是否前往安装',
					success: function(res) {
						if (res.confirm) {
							//需要通过webview打开的方式进行处理
							gotos(obj.iosurl)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			})
		}
		// #endif
		return
	}
}

//获取安卓手机已安装的浏览器 该方法需持续更新
const getbrowser = () => {
	let browser, isApplication
	let is_get = false
	//获取设备系统
	let res = uni.getSystemInfoSync();

	//优先检测手机品牌浏览器
	switch (res.brand) {
		case 'vivo':
			browser = isApplicationExist('com.vivo.browser');
			if (browser) {
				browser = 'com.vivo.browser'
			}
			break;
		case 'HUAWEI':
			browser = isApplicationExist('com.huawei.browser');
			if (browser) {
				browser = 'com.huawei.browser'
			}
			break;
		case 'Xiaomi':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'OPPO':
			browser = isApplicationExist('com.heytap.browser');
			if (browser) {
				browser = 'com.heytap.browser'
			}
			break;
		case 'realme':
			browser = isApplicationExist('com.heytap.browser');
			if (browser) {
				browser = 'com.heytap.browser'
			}
			break;
		case 'asus':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'OnePlus':
			browser = isApplicationExist('com.heytap.browser');
			if (browser) {
				browser = 'com.heytap.browser'
			}
			break;
		case 'samsung':
			browser = isApplicationExist('com.sec.android.app.sbrowser');
			if (browser) {
				browser = 'com.sec.android.app.sbrowser'
			}
			break;
		case 'Google':
			browser = isApplicationExist('com.android.chrome');
			if (browser) {
				browser = 'com.android.chrome'
			}
			break;
		case 'Meizu':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'HONOR':
			browser = isApplicationExist('com.huawei.browser');
			if (browser) {
				browser = 'com.huawei.browser'
			}
			break;
		case 'blackshark':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'Sony':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'Lenovo':
			browser = isApplicationExist('com.zui.browser');
			if (browser) {
				browser = 'com.zui.browser'
			}
			break;
		case 'smartisan':
			browser = isApplicationExist('com.android.browser');
			if (browser) {
				browser = 'com.android.browser'
			}
			break;
		case 'nubia':
			browser = isApplicationExist('com.nubia.browser');
			if (browser) {
				browser = 'com.nubia.browser'
			}
			break;
	}

	if (browser) {
		return browser
	}

	//品牌浏览器不存在时，按顺序进行下方浏览器检测
	let brand = [
		'com.android.browser', //通用浏览器 小米、asus、谷歌、魅族、黑鲨、索尼、smartisan等品牌手机均使用此默认浏览器
		'com.heytap.browser', //OPPO、REALME、OnePlus等品牌手机使用此默认浏览器
		'com.UCMobile', //UC浏览器
		'com.tencent.mtt', //QQ浏览器
		'com.baidu.searchbox', //百度浏览器
		'com.qihoo.browser', //360浏览器
		'sogou.mobile.explorer', //搜狗浏览器
		'com.ijinshan.browser_fast', //猎豹浏览器
		'com.oupeng.mini.android', //欧朋浏览器
		'org.mozilla.firefox', //火狐浏览器
		'com.android.chrome', //Chrome浏览器
		'com.microsoft.emmx', //edge浏览器
		'com.quark.browser', //夸克浏览器
		'com.baidu.searchbox.lite', //百度极速版浏览器
		'com.vivo.browser', //vivo品牌浏览器
		'com.huawei.browser', //华为品牌浏览器
		'com.sec.android.app.sbrowser', //三星品牌浏览器
		'com.zui.browser', //联想品牌浏览器
		'com.nubia.browser', //努比亚品牌浏览器
	]

	brand.forEach(function(value) {
		if (!is_get) {
			isApplication = isApplicationExist(value);
			if (isApplication) {
				is_get = true
				browser = value
			}
		}
	})

	return browser
}

const isApplicationExist = (value) => {
	let browser
	browser = plus.runtime.isApplicationExist({
		pname: value
	});
	if (browser) {
		return true
	} else {
		return false
	}
}

//系统
const wanlsys = () => {
	const sys = uni.getSystemInfoSync();
	const data = {
		top: sys.statusBarHeight,
		height: sys.statusBarHeight + uni.upx2px(90),
		screenHeight: sys.screenHeight,
		platform: sys.platform,
		model: sys.model,
		windowHeight: sys.windowHeight,
		windowBottom: sys.windowBottom,
		deviceId: sys.deviceId
	};
	// // #ifdef MP-WEIXIN || MP-BAIDU || MP-QQ || MP-TOUTIAO || MP-WEIXIN
	// const custom = uni.getMenuButtonBoundingClientRect();
	// data.height = custom.bottom + custom.top - sys.statusBarHeight;
	// // #endif		
	// #ifdef MP-ALIPAY
	data.height = sys.statusBarHeight + sys.titleBarHeight;
	// #endif
	return data;
}

// 音频
const audio = url => {
	return request_data.imageUrl + url
}

//图片 
const img = (url, type = '') => {
	console.log(99999999)
	if (request_data.imgcdn == 1) {
		//CDN远程程附件

		//是否开启阿里云图片处理
		if (request_data.imgcdn_aly_handle == 1) {
			//开启图片处理
			if (type != '') {
				let image = '';
				//当地址不存在
				if (url) {
					if ((/^data:image\//.test(url))) {
						image = url + '?x-oss-process=style/' + type;
					} else if ((/^(http|https):\/\/.+/.test(url))) {
						image = url + '?x-oss-process=style/' + type;
					} else {
						image = request_data.imageUrl + url + '?x-oss-process=style/' + type;
					}
				} else {

				}
				console.log(111, image)
				return image;
			} else {
				let image = '';
				//当地址不存在
				if (url) {
					if ((/^data:image\//.test(url))) {
						image = url;
					} else if ((/^(http|https):\/\/.+/.test(url))) {
						image = url;
					} else {
						image = request_data.imageUrl + url;
					}
				} else {

				}
				console.log(222, image)
				return image;
			}
		} else {
			let image = '';
			//当地址不存在
			if (url) {
				if ((/^data:image\//.test(url))) {
					image = url;
				} else if ((/^(http|https):\/\/.+/.test(url))) {
					image = url;
				} else {
					image = request_data.imageUrl + url;
				}
			} else {

			}
			console.log(222, image)
			return image;
		}

	} else {
		//未开启CDN远程附件
		let image = '';
		//当地址不存在
		if (url) {
			if ((/^data:image\//.test(url))) {
				image = url;
			} else if ((/^(http|https):\/\/.+/.test(url))) {
				image = url;
			} else {
				image = request_data.baseUrl + url;
			}
		} else {

		}
		console.log(image)
		return image;
	}

}

//上传图片
const uploadFile = (tempFilePaths, types) => {
	let token = uni.getStorageSync(request_data.storage().token);
	let sign = request_data.getsign();
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: request_data.baseUrl + '/api/xxnmupload/upload',
			filePath: tempFilePaths[0],
			name: 'avatar',
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'token': token || '',
				'sign': sign,
				'platformid':request_data.platformid
			},
			formData: {
				pic_type: types || ''
			},
			success: (uploadFileRes) => {
				let img = JSON.parse(uploadFileRes.data)
				if (img.msg == '非法图片文件') {
					uni.showToast({
						title: '非法图片文件',
						icon: 'none'
					})
					return
				}
				resolve(img.data.url)
			},
			fail: (err => {
				reject(err)
			})
		});
	})
}

//页面栈管理
const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	// #ifdef H5
	return prePage;
	// #endif
	return prePage.$vm;
}

//顶部导航栏
const title = (text = '', setbar = {}) => {
	if (text) {
		uni.setNavigationBarTitle({
			title: text
		});
	}
	if (JSON.stringify(setbar) != "{}") {
		uni.setNavigationBarColor(setbar);
	}
}

//微信授权登录
const login = (type) => {
	return new Promise((resolve, reject) => {
		// #ifdef MP-WEIXIN
		uni.getUserProfile({
			desc: '用于登录',
			success: res => {
				request_data.request("/api/xxnmuser/login", {
					iv: res.iv,
					encryptedData: res.encryptedData,
					code: uni.getStorageSync(request_data.storage().wxcode),
					token_type: 1,
					gender: res.userInfo.gender
				}).then((res) => {
					uni.removeStorageSync(request_data.storage().wxcode)
					resolve(res)
				}).catch(err => {
					console.log('getUserProfile', err)
				});
			}
		})

		// #endif
		// #ifdef APP-PLUS
		uni.login({
			provider: type,
			success: (data) => {
				uni.getUserInfo({
					success: (res) => {
						resolve(res.userInfo)
					}
				})
			},
			fail: (err) => {
				reject(err)
			}
		})
		// #endif
	})
}

//权限检测
const check_auth = (arr) => {
	if (arr.length == 0) {
		return true
	}

	if (arr.indexOf('token') != -1) {
		let token = uni.getStorageSync(request_data.storage().token)
		if (!token) {
			// #ifdef APP-PLUS
			on('/pages/login/login')
			// #endif
			return false
		}
	}

	return true
}


//权限检测
request_data.check_auth = check_auth
//加法精度计算
request_data.bcadd = bcadd
//乘法精度计算
request_data.bcmul = bcmul
//减法精度计算
request_data.bcsub = bcsub
//统一提示方便全局修改
request_data.msg = msg
//页面返回
request_data.back = back
//页面跳转
request_data.on = on
//解析地址
request_data.ons = ons
//跳转链接
request_data.gotos = gotos
//系统
request_data.wanlsys = wanlsys
//音频
request_data.audio = audio
//图片
request_data.img = img
//上传图片
request_data.uploadFile = uploadFile
//页面栈管理
request_data.prePage = prePage
//顶部导航栏
request_data.title = title
//微信授权登录
request_data.login = login

export default request_data
